<template>
  <div class="container">
    <el-row class="">
      <el-col :span="16" align="left">
        <el-input clearable v-model="search.name" placeholder="成果名称" style="width: 150px; margin-right: 15px">
        </el-input>
        <!-- <el-select clearable v-model="search.unitId" placeholder="完成单位" style="width: 150px">
          <el-option :label="item.name" :value="item.id" :key="item.id" v-for="item in unitNameList" />
        </el-select> -->

        <div class="conUnitName">
          <el-cascader @change="changeUnit" popper-class="gy-cascader" :options="unitNameList" :props="popupTreeProps"
            v-model="search.unitId" :show-all-levels="false" placeholder="请选择完成单位" clearable>
            <template #default="{ data }">
              <el-tooltip :disabled="data.name.length < 13" class="item" effect="dark" :content="data.name"
                placement="bottom-start">
                <span>{{ data.name }}</span>
              </el-tooltip>
            </template>
          </el-cascader>
        </div>

        <el-select clearable v-model="search.levelId" placeholder="评价级别" @change="changeCommentLevel"
          style="width: 150px">
          <el-option :label="item.itemText" :value="item.itemValue" :key="item.itemValue" v-for="item in levelList" />
        </el-select>

        <el-select clearable v-model="search.themeFormId" placeholder="主题及形式" v-if="search.levelId" style="width: 150px">
          <el-option :label="item.itemText" :value="item.itemValue" :key="item.itemValue" v-for="item in methodType" />
        </el-select>

        <el-button class="ordinary" @click="getTableList" style="margin-left: 15px">搜索</el-button>
      </el-col>
      <el-col :span="8" align="right">
        <el-button class="unlock" @click="getUnlockBtn()" v-limit="'KJSL:KJCG:CGPJ:UNLOCK'">解锁</el-button>
        <el-button class="lock" @click="getLockBtn()" v-limit="'KJSL:KJCG:CGPJ:LOCK'">锁定</el-button>
        <el-button class="ordinary" @click="getExportBtn()"  v-limit="'KJSL:KJCG:CGPJ:EXPERT'">批量导出</el-button>
        <el-button type="danger" @click="handleDetect()"  v-limit="'KJSL:KJCG:CGPJ:DELETE'">批量删除</el-button>
        <el-button type="primary" @click="handleAdd()"  v-limit="'KJSL:KJCG:CGPJ:ADD'">新增</el-button>
      </el-col>
    </el-row>
    <div>
      <Table :loading="isLoading" :tableArr="tableDate" :pagination="pagination" :columns="columns"
       @selectItem="getCurrentList" :total="pagination.total" @delectTable="delectIds" @currentChange="currentChange" @sizeChange="sizeChange">
        <template #status="{ row }">
          <span v-if="row.isLock == 1">已锁定</span>
          <span v-else>
            <span v-if="row.status == 0" style="color: #e6a23c">待确认</span>
            <span v-if="row.status == 1" style="color: #67c23a">已确定</span>
            <span v-if="row.status == 2" style="color: #67c23a">正常</span>
          </span>
        </template>
        <template #operate="{ row }">
          <el-button size="small" class="ordinary" v-show="row.updateFlag" :key="row.id + 'bj'" :disabled="row.isLock == 1"  v-limit="'KJSL:KJCG:CGPJ:EDIT'"
            @click="handleEdit(row)">编辑</el-button>
          <el-button size="small" class="ordinary" :key="row.id + 'bj'"
                     @click="handleDetail(row)">详情</el-button>
          <el-button v-if="row.status == '0'" size="small" type="primary" :key="row.id + 'qr'" :disabled="row.isLock == 1"   v-limit="'KJSL:KJCG:CGPJ:CONFIRM'"
            @click="handleConfirm(row)">确认</el-button>
        </template>
      </Table>
    </div>
    <InfoDialog :dialogVisable="infoDialog" :id="id" :flag="flag" @changeDialog="changeDialog" :orgAllList="unitNameList"></InfoDialog>
    <InfoDialogxq :dialogVisableXq="infoDialogxq" :id="id" :flag="flag" @changeDialogxq="changeDialogxq" :orgAllList="unitNameList"></InfoDialogxq>
  </div>
</template>
<script>
import * as proxy from "@/constants/proxy";
import request from "@/utils/request";
import {
getConfirm,
getDelect,
getDictionary,
getExport,
getLock,
getTable,
getUnlock
} from "@/views/science/api/assessmen";
import SelectOption from "@/views/science/components/selectOption/index.vue";
import Table from "@/views/science/components/table/TableDate.vue";
import { Modals, tips } from "@/views/science/components/tips/tips";
import InfoDialog from "@/views/science/payoffs/assessmentresults/InfoDialog.vue";
import InfoDialogxq from "@/views/science/payoffs/assessmentresults/InfoDialogxq.vue";
import { onMounted, reactive, toRefs } from "vue";
import { useStore } from "vuex";
import { ElMessage } from 'element-plus';
import tableHead from "./tableHeader.json";

import moment from "moment";

export default {
  components: {
    SelectOption,
    Table,
    InfoDialog,
    InfoDialogxq,
  },
  setup() {
    const store = useStore();

    // 发送请求
    onMounted(() => {
      // 获取数据字典
      getCodeList();
      // 获取单位
      getUnitList();
      // 列表信息table
      getTableList();
    });

    let data = reactive({
      popupTreeProps: {
        label: 'name',
        children: 'children',
        value: 'id',
        checkStrictly: true,
      },
      orgAllList: [],
      id: "",
      flag: 1,
      infoDialog: false,
      ids: [],
      pagination: { page: 1, limit: 10, total: 0 }, //分页
      isLoading: false,
      unitNameList: [], //维护单位
      levelList: [], //评论登记
      tableDate: [],
      methodType: [],
      columns: tableHead.assessmentHeader,
      search: {
        name: "",
        unitId: "",
        levelId: "",
        themeFormId: "",
      },
      selectedRows: [],
      infoDialogxq:false,
    });
    // 详情
    let handleDetail = (row) => {
      data.flag = 3;
      data.id = row.id;
      data.infoDialogxq = true;
    };

    let changeDialogxq = (value) => {
      data.id = "";
      data.flag = 1;
      // 分页刷新列表
      data.infoDialogxq = false;
    }

    // 解锁
    let getUnlockBtn = async () => {
      if (data.ids.length == 1) {
        Modals("是否解锁选择内容", "提示", "warning")
          .then(async () => {
            let res = await getUnlock(data.ids);
            if (res.data.success) {
              tips("解锁成功", "success");
              getTableList();
            }
          })
          .catch(() => {
            console.log("点击了取消");
          });
      } else if (data.ids.length == 0) {
        tips("请选择", "warning");
      } else {
        tips("解锁功能不可批量操作", "warning");
      }
    };
    //  锁定
    let getLockBtn = async () => {
      if (data.ids.length == 1) {
        let flag = true
        console.log(data.selectedRows, 'selectedRows')
        data.selectedRows.forEach((obj) => {
          if (obj.status == '0') {
            flag = false
          }
        })
        if (!flag) {
          ElMessage({
            message: '请确认后再进行锁定',
            type: 'warning',
          })
          return
        }
        Modals("是否锁定选择内容", "提示", "warning")
          .then(async () => {
            let res = await getLock(data.ids);
            if (res.data.success) {
              tips("锁定成功", "success");
              getTableList();
            }
          })
          .catch(() => {
            console.log("点击了取消");
          });
      } else if (data.ids.length == 0) {
        tips("请选择", "warning");
      } else {
        tips("锁定功能不可批量操作", "warning");
      }
    };

    // 导出功能的实现

    let getExportBtn = () => {
      let msg = '是否导出全部数据'
      if(data.ids.length>0){
        msg = '是否导出所选数据'
      }
      Modals(msg, "提示", "warning")
        .then(async () => {
          const params = {
            ...data.search,
            ids: data.ids
          }
          await getExport(params, "成果评价");
        })
        .catch(() => {
          console.log("点击了取消");
        });
    };
    // 确定当前流程
    let handleConfirm = async (row) => {
      Modals("是否确认当前流程", "提示", "warning")
        .then(async () => {
          let res = await getConfirm(row.id);
          if (res.data.success) {
            getTableList();
          }
        })
        .catch(() => { });
    };

    // 批量删除

    const handleDetect = async () => {
      if (data.ids.length) {
        Modals("是否删除选择内容", "提示", "warning")
          .then(async () => {
            let res = await getDelect(data.ids);
            if (res.data.success) {
              tips("删除成功", "success");
              getTableList();
            }
          })
          .catch(() => {
            console.log("点击了取消");
          });
      } else {
        tips("请选择", "warning");
      }
    };

    // 获取列表信息
    let getTableList = () => {
      (data.isLoading = true),
        getTable({
          current: data.pagination.page,
          size: data.pagination.limit,
          ...data.search,
        }).then((res) => {
          let resData = res.data.data.records;
          resData.map((item) => {
            item.approvalDate = moment(item.approvalDate).format("YYYY-MM-DD");
          });
          data.tableDate = res.data.data.records;
          data.pagination.total = res.data.data.total;
          data.isLoading = false;
        }).catch(err=>{
          data.isLoading = false;
        });
    };

    // 分页

    let currentChange = (current) => {
      data.pagination.page = current;

      getTableList();
    };

    const sizeChange = (size) => {
      console.log(size)
      data.pagination.limit = size
      getTableList()
    }
    const getCurrentList = (currentList) => {
      console.log(currentList, 'getCurrentList')
      data.selectedRows = currentList
    }
    // 获取ids

    let delectIds = (ids) => {
      data.ids = ids;
    };

    // 单位
    let getUnitList = () => {
      return request({
        url: proxy.CHECC_API_CMS + "/org/getSysOrgList",
        method: "get",
      }).then(res => {
        data.unitNameList = res.data.data
      })
    };

    let changeUnit = (val) => {
      if (val == null) {
        data.search.unitId = ''
        return false
      }
      if (val.length > 0) {
        let unitId = val[val.length - 1]
        data.search.unitId = unitId
      }
    }

    //  用户列表
    let getCodeList = () => {
      getDictionary(["KJSL_EVALUATION_LEVEL_EVALUATION_SUBJECT"]).then((res) => {
        data.levelList = res.data.data.KJSL_EVALUATION_LEVEL_EVALUATION_SUBJECT;
      });
    };

    // 新增
    let handleAdd = () => {
      data.flag = 1;

      data.infoDialog = true;
    };
    // 编辑

    let handleEdit = (row) => {
      data.flag = 2;
      data.id = row.id;
      data.infoDialog = true;
    };

    let changeDialog = (value) => {
      data.id = "";
      data.flag = 1;

      if (value) {
        data.pagination.page = 1;
        getTableList();
      }
      // 分页刷新列表
      data.infoDialog = false;
    };

    // 评论级别

    let changeCommentLevel = (id) => {

      let arrList = data.levelList.find((item) => item.itemValue == id).children;

      if (arrList.length > 0) {
        data.methodType = arrList;
      }

      data.search.levelId = id;

      data.search.themeFormId = "";
    };

    return {
      ...toRefs(data),
      store,
      changeCommentLevel,
      handleEdit,
      handleAdd,
      changeDialog,
      getTableList,
      getLockBtn,
      getExportBtn,
      getUnlockBtn,
      getCurrentList,
      delectIds,
      handleConfirm,
      handleDetect,
      currentChange,
      sizeChange,
      getUnitList,
      changeUnit,
      changeDialogxq,
      handleDetail,
    };
  },
};
</script>
<style lang="scss" >
.container {
  background-color: white !important;
  padding: 20px;
}

.conUnitName {
  display: inline-block;
  width: 200px;
}

.gy-cascader {
  .el-cascader-node {
    max-width: 250px;
  }
}
</style>
